package app.sevenc.lib_framework.permission

import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentActivity
import com.blankj.utilcode.util.ToastUtils
import com.permissionx.guolindev.PermissionMediator
import com.permissionx.guolindev.PermissionX

/**
 * 郭霖权限请求实现类
 *
 * @author Seven-C
 * @date 2021/8/23
 */
class GuolindevPermissionImpl : IPermission {

    override fun activityPermissions(
        activity: FragmentActivity,
        permissions: List<String>,
        action: (Boolean) -> Unit
    ) {
        permissions(PermissionX.init(activity), permissions, action)
    }

    override fun fragmentPermissions(
        fragment: Fragment,
        permissions: List<String>,
        action: (Boolean) -> Unit
    ) {
        permissions(PermissionX.init(fragment), permissions, action)
    }

    private fun permissions(
        permissionMediator: PermissionMediator,
        permissions: List<String>,
        action: (Boolean) -> Unit
    ) {
        permissionMediator.permissions(permissions)
            .onExplainRequestReason { scope, deniedList, beforeRequest ->
                val message = "需要以下权限才能继续"
                scope.showRequestReasonDialog(deniedList, message, "允许", "拒绝")
            }
            .onForwardToSettings { scope, deniedList ->
                val message = "请在设置中允许以下权限"
                val dialog = PermissionDialogFragment(message, deniedList)
                scope.showForwardToSettingsDialog(dialog)
            }
            .request { allGranted, grantedList, deniedList ->
//                LogUtils.dTag(DEBUG_TAG,"permissionMediator permissions $grantedList")
                if (allGranted) {
                    //授予所有权限
//                    ToastUtils.showShort("授予所有权限")
                } else {
                    ToastUtils.showShort("权限被拒绝")
                }
                action(allGranted)
            }
    }
}